﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

using HST.Infrastructure.Data.Seedwork;
using HST.ZWParking.Domain.Entities;
using HST.ZWParking.Infrastructure.Data.EntityFramework.Mapping;

namespace HST.ZWParking.Infrastructure.Data.EntityFramework
{
    public class ZWParkingContext : DbContext, IDataContext
    {
        static ZWParkingContext()
        {
            Database.SetInitializer<ZWParkingContext>(null);
        }

        public DbSet<Province> Provinces { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Remove unused conventions
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

            //Add entity maps in a structured way using 'TypeConfiguration’ classes
            modelBuilder.Configurations.Add(new ProvinceMap());
        }

        #region IDataContext Members

        public DbSet<TAggregateRoot> CreateSet<TAggregateRoot>()
            where TAggregateRoot : class
        {
            return base.Set<TAggregateRoot>();
        }

        public void SetModified<TAggregateRoot>(TAggregateRoot aggregateRoot)
            where TAggregateRoot : class
        {
            base.Entry<TAggregateRoot>(aggregateRoot).State = System.Data.EntityState.Modified;
        }

        public void Commit()
        {
            base.SaveChanges();
        }

        public void Rollback()
        {
            base.ChangeTracker.Entries()
                              .ToList()
                              .ForEach(entry => entry.State = System.Data.EntityState.Unchanged);
        }

        public IEnumerable<TAggregateRoot> ExecuteQuery<TAggregateRoot>(string sqlQuery, params object[] parameters)
        {
            return base.Database.SqlQuery<TAggregateRoot>(sqlQuery, parameters);
        }

        public int ExecuteCommand(string sqlCommand, params object[] parameters)
        {
            return base.Database.ExecuteSqlCommand(sqlCommand, parameters);
        }
        #endregion
    }
}
